package com.alphaking.Jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.collections.set.SynchronizedSet;

import com.mysql.jdbc.PreparedStatement;

public class JdbcUser {

	// 数据库连接
	private static Connection con = JdbcUtils.getCon();

	/**
	 * 登陆时账号密码的检验
	 * 
	 * @param account
	 *            账号
	 * @param password
	 *            密码
	 * @return
	 */
	public static int check_login(String account, String password) {

		try {
			java.sql.PreparedStatement pstmt = con.prepareStatement("select * from user where user_account=?");
			pstmt.setString(1, account);
			ResultSet rst = pstmt.executeQuery();

			if (rst.next()) {

				String realpassword = rst.getString("password");
				
				if (realpassword.equals(password)) {
					
					int count = rst.getInt("registerTimes") + 1;
		
					
					pstmt = (PreparedStatement) con
							.prepareStatement("update user set registerTimes = ? where user_account = ?");

					pstmt.setInt(1, count);

					pstmt.setString(2, account);
					pstmt.execute();
					
					return 3;
					
				} else {
					return 2;
				}

			} else {

				return 1;
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 1;
	}
	/**
	 * 注册
	 */
	public static boolean register(String account, String password) {

		String insert = "insert into user(user_account,password,registerdate) values(?,?,?)";

		try {

			PreparedStatement pstmt = (PreparedStatement) con.prepareStatement(insert);
			pstmt = (PreparedStatement) con.prepareStatement(insert);
			pstmt.setString(1, account);
			pstmt.setString(2, password);
			pstmt.setString(3, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			pstmt.execute();
			return true;

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 判断这个用户是否存在
	 * 
	 * @param account
	 * @return
	 */
	public static boolean checkAccount(String account) {

		String search = "select * from user where user_account = ?";
		try {
			PreparedStatement pstmt = (PreparedStatement) con.prepareStatement(search);
			pstmt.setString(1, account);
			ResultSet rst = pstmt.executeQuery();
			if (rst.next()) {
				return true;
			} else {
				return false;
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;

	}

}
